package com.heima.media.listener;

import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * 监听文章发布时间
 *
 * @Name : PublishArticleListener
 * @Author : WuQiang
 * @Date : 2022-10-13 22:22
 * @Description : 监听文章发布时间
 */
@Slf4j
@Component
public class PublishArticleListener {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private IAuditService auditService;
    @Autowired
    private IWmNewsService wmNewsService;

    @PostConstruct
    public void receiveMessages() {
        RBlockingQueue<Integer> blockingQueue = redissonClient.getBlockingQueue("article-queue");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Integer wmNewsId = blockingQueue.poll(30, TimeUnit.SECONDS);
                        if (wmNewsId != null) {
                            //发布app文章
                            //根据id查询
                            WmNews wmNews = wmNewsService.getById(wmNewsId);
                            Long articleId = auditService.saveArticle(wmNews);
                            wmNews.setArticleId(articleId);
                            wmNews.setStatus(9);
                            wmNewsService.updateById(wmNews);
                            log.info("延迟任务发布成功");
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        throw new RuntimeException("延迟发布失败");
                    }
                }
            }
        }).start();
    }
}
